package com.codermn.并发访问控制.计数器CountDownLatch.案例2;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *     有4个线程分别获取C、D、E、F盘的大小, 第5个线程统计总大小
 * </p>
 * @author jxau_scf
 * @date 2021/9/6 - 10:47
 */
public class DiskMemory {
    private int totalSize;
    public int getSize(){
        return (new Random().nextInt(3) + 1) * 100;
    }
    public synchronized void setSize(int size){
        this.totalSize += size;
    }
    public int getTotalSize(){
        return this.totalSize;
    }

    public static void main(String[] args) throws InterruptedException {
        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        CountDownLatch countDownLatch = new CountDownLatch(4);
        DiskMemory diskMemory = new DiskMemory();
        for (int i = 0;i < 4; i++){
            executorService.execute(()->{
                int timer = new Random().nextInt(5);
                try {
                    Thread.sleep(timer * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int size = diskMemory.getSize();
                System.out.printf("完成磁盘的统计任务,耗费%d秒. 磁盘大小为%d.\n", timer, size);
                diskMemory.setSize(size);

                //完成任务，计数器减一
                countDownLatch.countDown();
                System.out.println("count num = " + countDownLatch.getCount());

            });
        }
        countDownLatch.await();
        System.out.printf("全部磁盘都统计完成,所有磁盘总大小为 " + ", 【 totalSize = " + diskMemory.getTotalSize() + " 】");
        //关闭线程池
        executorService.shutdown();
    }

}
